/**
 * $Id$
 */
package jm.lib.util;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * @author Jiming Liu
 *
 */
public class ObjectUtil {
	static MethodInterceptor roInterceptor;
	static {
		roInterceptor = new MethodInterceptor() {

			/* (non-Javadoc)
			 * @see net.sf.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], net.sf.cglib.proxy.MethodProxy)
			 */
			public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
				if(method.getName().startsWith("set")) {
					throw new RuntimeException("aaaaaaaaaaaa");
				} else {
					return proxy.invokeSuper(obj, args);
				}
			}
		};
	}
	
    public static  Object newInstance( Class clazz ){
        try{
        	//return Enhancer.create(clazz, roInterceptor)
            Enhancer e = new Enhancer();
            e.setSuperclass(clazz);
            e.setCallback(roInterceptor);
            Object bean = e.create();
            // interceptor.propertySupport = new PropertyChangeSupport( bean );
            return bean;
        }catch( Throwable e ){
            e.printStackTrace();
            throw new Error(e.getMessage());
        }
        
    }
    
	public static <T> T getReadOnlyInstance(T o) {
		return (T)Enhancer.create(o.getClass(), roInterceptor);
		// return (T)newInstance(o.getClass());
	}
}
